#include <vector>
#include<array>
#include <iostream>
#include<limits>
#include <ostream>

class Solution
{
public:
    const static int MAX = 3000001;
    std::array<std::array<int, 2>, MAX> tree;
    int cnt = 1;
    int left = 0;

    int findMaximumXOR(std::vector<int>& nums)
    {
        build(nums);
        int ans = 0;
        for (int num : nums)
        {
            ans = std::max(ans, cal(num));
            std::cout<<ans<<std::endl;
        }
        return ans;
    }

    void build(std::vector<int>& nums)
    {
        int max = std::numeric_limits<int>::min();
        for (int num : nums)
        {
            max = std::max(max, num);
        }
        left = 31 - countLeadingZeros(max);

        for (int num : nums)
        {
            insert(num);
        }
    }


    int cal(int num)
    {
        int max = std::numeric_limits<int>::min();
        int ans = 0;
        int index = 1;
        for (int i = left, status, want; i >= 0; i--)
        {
            status = (num >> i) & 1;
            want = status ^ 1;
            if (tree[index][want] == 0 )
            {
                want ^= 1;
            }
            ans |= want << i;
            index = tree[index][want];
        }
        return ans^ num;
    }

    void insert(int num)
    {
        int cur = 1;
        for (int i = left, path; i >= 0; i--)
        {
            path = (num >> i) & 1;
            if (tree[cur][path] == 0)
            {
                tree[cur][path] = ++cnt;
            }
            cur = tree[cur][path];
        }
    }

    int countLeadingZeros(int x)
    {
        if (x == 0) return sizeof(x) * 8; // 若x为0，返回全部位数

        int count = 0;
        // 从最高位开始检查
        for (int i = sizeof(x) * 8 - 1; i >= 0; i--)
        {
            if ((x & (1 << i)) == 0)
            {
                count++;
            }
            else
            {
                break; // 一旦遇到第一个1，就停止计数
            }
        }
        return count;
    }
};
